import { ref } from "vue"
import { pinia } from "@/store"
import { defineStore } from "pinia"
import { type RouteRecordRaw } from "vue-router"
import { router, constantRoutes, dynamicRoutes } from "@/router"
import { flatMultiLevelRoutes } from "@/router/helper"
import routeSettings from "@/config/route"
import { getRouters } from "@/api/system/menu"
const Layouts = () => import("@/layouts/index.vue")
import ParentView from "@/components/ParentView/index.vue"
// import InnerLink from "@/layout/components/InnerLink/index.vue";

const hasPermission = (roles: string[], route: RouteRecordRaw) => {
  const routeRoles = route.meta?.roles
  return routeRoles ? roles.some((role) => routeRoles.includes(role)) : true
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap: any[], lastRouter = false, type = false) {
  return asyncRouterMap.filter((route) => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
      console.log("route.children", route.children)
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === "Layout") {
        route.component = Layouts
      } else if (route.component === "ParentView") {
        route.component = ParentView
      }
      // else if (route.component === "InnerLink") {
      // 	route.component = InnerLink;
      // }
      else {
        // route.component = loadView(route.component);
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route["children"]
      delete route["redirect"]
    }
    return true
  })
}

function filterChildren(childrenMap: any[], lastRouter?: any) {
  console.log("childrenMap", childrenMap)
  let children: any[] = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      console.log("el.component", el.component)
      console.log("el.component === ParentView", el.component === "ParentView")
      if (el.component === "ParentView" && !lastRouter) {
        el.children.forEach((c: any) => {
          c.path = el.path + "/" + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + "/" + el.path
    }
    children = children.concat(el)
  })
  return children
}

const filterDynamicRoutes = (routes: RouteRecordRaw[], roles: string[]) => {
  const res: RouteRecordRaw[] = []
  routes.forEach((route) => {
    const tempRoute = { ...route }
    if (hasPermission(roles, tempRoute)) {
      if (tempRoute.children) {
        tempRoute.children = filterDynamicRoutes(tempRoute.children, roles)
      }
      res.push(tempRoute)
    }
  })
  return res
}

export const usePermissionStore = defineStore("permission", () => {
  const routes = ref<RouteRecordRaw[]>([])
  /** 有访问权限的动态路由 */
  const addRoutes = ref<RouteRecordRaw[]>([])

  /** 根据角色生成可访问的 Routes（可访问路由 = 常驻路由 + 有访问权限的动态路由） */
  const setRoutes = (roles: string[]) => {
    console.log("动态路由", dynamicRoutes)
    console.log("常驻路由", constantRoutes)
    getRouters()
      .then((res) => {
        const rdata = JSON.parse(JSON.stringify(res.data))
        console.log("rdata", rdata)
        const rewriteRoutes = filterAsyncRouter(rdata, false, true)
        console.log("rewriteRoutes", rewriteRoutes)
        const asyncRoutes = filterDynamicRoutes(dynamicRoutes, roles)
        console.log("asyncRoutes", asyncRoutes)
        // const accessedRoutes = asyncRoutes.concat(JSON.parse(JSON.stringify({})))
        const accessedRoutes = asyncRoutes.concat(rewriteRoutes)
        console.log("accessedRoutes", accessedRoutes)
        addRoutes.value = accessedRoutes
        routes.value = constantRoutes.concat(accessedRoutes)
        console.log("routes.value", routes.value)
      })
      .catch((err) => {
        console.log("err", err)
      })

    // const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
    // _set(accessedRoutes)
  }

  /** 所有路由 = 所有常驻路由 + 所有动态路由 */
  // const setAllRoutes = () => {
  //   _set(asyncRoutes)
  // }

  // const _set = (accessedRoutes: RouteRecordRaw[]) => {
  //   routes.value = constantRoutes.concat(accessedRoutes)
  //   dynamicRoutes.value = routeSettings.thirdLevelRouteCache ? flatMultiLevelRoutes(accessedRoutes) : accessedRoutes
  // }

  return { routes, dynamicRoutes, addRoutes, setRoutes }
})

/**
 * 在 SPA 应用中可用于在 pinia 实例被激活前使用 store
 * 在 SSR 应用中可用于在 setup 外使用 store
 */
export function usePermissionStoreHook() {
  return usePermissionStore(pinia)
}
